package com.xiaoyang.billiards.architecture.handler;

import com.xiaoyang.billiards.architecture.common.Errors.ServiceError;
import com.xiaoyang.billiards.architecture.common.exception.ServiceException;
import com.xiaoyang.billiards.architecture.common.result.Result;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 杨泽纬
 * @description 捕获全局异常处理类
 * @serviceName XiaoYangExceptionHandler
 * @date 2023/11/16
 */
@RestControllerAdvice(basePackages = "com.xiaoyang.billiards.controller")
@Slf4j
@Order(0)
public class XiaoYangExceptionHandler {

    @ExceptionHandler(value = ServiceException.class)
    public Result<Void> Exception(ServiceException e) {
        log.error("**************ServiceException**************");
        log.error("业务异常", e);
        return Result.error(e);
    }


    @ExceptionHandler(value = Exception.class)
    public Result<Void> Exception(Exception e) {
        log.error("**************Exception**************");
        log.error("接口未知异常", e);
        String message = e.getMessage();
        if (Objects.isNull(message)) {
            message = Arrays.stream(e.getStackTrace()).limit(10).map(StackTraceElement::toString).collect(Collectors.joining("\n"));
        }
        return Result.error(ServiceError.SYSTEM_ERROR, message);
    }

    @ExceptionHandler(value = NullPointerException.class)
    public Result<Void> nullException(NullPointerException e) {
        log.error("**************NullPointerException**************");
        log.error("接口空指针异常", e);
        return Result.error(ServiceError.SYSTEM_ERROR, "空指针异常");
    }

    @PostConstruct
    public void init() {
        log.info("捕获全局异常处理启动完成");
    }


}
